package com.clas.liu.myapplication.view.fragment.impl;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.model.entity.info.Info;
import com.clas.liu.myapplication.model.entity.info.InfoData;
import com.clas.liu.myapplication.model.entity.user.UserData;
import com.clas.liu.myapplication.model.event.UserEvent;
import com.clas.liu.myapplication.presenter.impl.BaseFragmentPresenter;
import com.clas.liu.myapplication.presenter.impl.UserFragmentPresenter;
import com.clas.liu.myapplication.view.activity.impl.EditActivity;
import com.clas.liu.myapplication.view.activity.impl.LoginActivity;
import com.clas.liu.myapplication.view.activity.impl.MainActivity;
import com.clas.liu.myapplication.view.activity.impl.SettingActivity;
import com.clas.liu.myapplication.view.adapter.UserItemAdapter;
import com.clas.liu.myapplication.view.fragment.i.IUserFragment;
import com.clas.liu.myapplication.view.util.NetworkHelper;
import com.clas.liu.myapplication.view.util.SaveUtil;
import com.clas.liu.myapplication.view.widget.CircleImageView;
import com.clas.liu.myapplication.view.widget.MainTabButton;
import com.squareup.picasso.Picasso;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liu on 2019/3/3.
 */

public class UserFragment extends BaseFragment<UserFragmentPresenter> implements IUserFragment, View.OnClickListener {

    private View root;
    private AppBarLayout appBarLayout;
    private MainTabButton setting;
    private SwipeRefreshLayout refreshLayout;
    private TextView title;
    private TextView userName;
    private ImageView sex;
    private TextView totalCount;
    private TextView selltedCount;
    private TextView school;
    private TextView zhuanye;
    private TextView introduction;
    private TextView age;
    private RelativeLayout totalView;
    private RelativeLayout solvedView;

    private RecyclerView recyclerView;
    private UserItemAdapter adapter;
    private LinearLayoutManager layoutManager;
    private Context context;

    private int page_no = 1;
    private final int page_size = 10;
    private List<Info> infos;
    private boolean isRefresh = true;
    private boolean isAll = false;
    private int lastVisibleItem;
    private UserData userData;
    private Handler handler;
    private int infoType = 0;
    private int userId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        root = inflater.inflate(R.layout.user_layout, container, false);
        findView();
        init();
        setListener();
        return root;
    }

    @Override
    protected UserFragmentPresenter getPresenter() {
        return new UserFragmentPresenter(this);
    }

    private void init() {
        handler = new Handler();
        refreshLayout.setRefreshing(true);
        initUserInfo();
    }

    private void initUserInfo() {
        try {
            userData = SaveUtil.<UserData>getFromLocal(context.getApplicationContext(), "user");
        } catch (Exception e) {
            e.printStackTrace();
            showToast("当前登录异常，重新登录！");
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            ((MainActivity) context).finish();
            return;
        }

        if (userData == null || userData.getId() == 0) {
            showToast("当前登录异常，重新登录！");
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            ((MainActivity) context).finish();
            return;
        }
        age.setText(String.valueOf(userData.getAge()));
        if (userData.getSchool() == null || userData.getSchool().equals("") || userData.getSchool().equals("null"))
            school.setText("学院未填写");
        else school.setText(userData.getSchool());
        if (userData.getInstitute() == null || userData.getInstitute().equals("") || userData.getInstitute().equals("null"))
            zhuanye.setText("专业未填写");
        else zhuanye.setText(userData.getInstitute());
        if (userData.getIntroduction() == null || userData.getIntroduction().equals("") || userData.getIntroduction().equals("null"))
            introduction.setText("快去编辑签名吧！");
        else introduction.setText(userData.getIntroduction());
        userName.setText(userData.getName());
        if (userData.getSex().equals("男"))
            sex.setImageResource(R.mipmap.man);
        else sex.setImageResource(R.mipmap.woman);
        isRefresh = true;
        mPresenter.getInfos(userData.getId(), infoType, page_no, page_size);
    }

    private void setListener() {
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset != 0) {
                    refreshLayout.setEnabled(false);
                    if (appBarLayout.getTotalScrollRange() - Math.abs(verticalOffset) <= 20) {
                        title.setText(userData.getName());
                        if (setting.getLv() != null) {
                            setting.getLv().setImageResource(R.mipmap.setting1);
                        }
                    } else {
                        title.setText(" ");
                        if (setting.getLv() != null) {
                            setting.getLv().setImageResource(R.mipmap.setting);
                        }
                    }
                } else {
                    refreshLayout.setEnabled(true);
                }
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                infoRefresh();
            }
        });
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (adapter != null && newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount()) {
                    if (!isAll)
                        mPresenter.getInfos(userData.getId(), infoType, page_no, page_size);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        solvedView.setOnClickListener(this);
        totalView.setOnClickListener(this);
        setting.setOnClickListener(this);
    }

    public void infoRefresh() {
        if (NetworkHelper.isNetworkAvailable(getActivity())) {
            page_no = 1;
            isRefresh = true;
            mPresenter.getInfos(userData.getId(), infoType, page_no, page_size);
        } else {
            refreshLayout.setRefreshing(false);
            showToast("亲亲，网好像断了呢!~");
        }
    }

    private void findView() {
        appBarLayout = root.findViewById(R.id.user_appbar_layout);
        setting = root.findViewById(R.id.user_setting_bt);
        refreshLayout = root.findViewById(R.id.user_refresh_layout);
        title = root.findViewById(R.id.user_title);
        recyclerView = root.findViewById(R.id.user_rv);
        userName = root.findViewById(R.id.user_name);
        sex = root.findViewById(R.id.user_sex);
        totalCount = root.findViewById(R.id.user_info_count);
        selltedCount = root.findViewById(R.id.user_solved_count);
        school = root.findViewById(R.id.user_school);
        zhuanye = root.findViewById(R.id.user_zhuanye);
        introduction = root.findViewById(R.id.user_introduction);
        age = root.findViewById(R.id.user_age);
        totalView = root.findViewById(R.id.user_total_view);
        solvedView = root.findViewById(R.id.user_solved_view);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        context = null;
    }

    @Override
    public void FailBecauseNetReturn(int code) {
        refreshLayout.setRefreshing(false);
        showToast("请求失败！");
        if (code!= UserEvent.GET_USER_INFO_FAIL) {
            adapter.getWindow().dismiss();
        }
    }

    @Override
    public void infoReturn(int type, final InfoData data) {
        if (infos == null) {
            infos = new ArrayList<>();
        }
        if (isRefresh) {
            infos.clear();
            isRefresh = false;
        }
        infos.addAll(data.getData());
        handler.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(false);
                if (isRefresh) {
                    if (adapter != null)
                        adapter.deleteLoadingMore(false);
                }
                if (infoType == 0) {
                    selltedCount.setText(String.valueOf(data.getSettledCount()));
                    totalCount.setText(String.valueOf(data.getTotal()));
                }
                recyclerView.setVisibility(View.VISIBLE);
                refreshLayout.setRefreshing(false);
                if (layoutManager == null) {
                    layoutManager = new LinearLayoutManager(context);
                    recyclerView.setLayoutManager(layoutManager);
                }
                if (adapter == null) {
                    adapter = new UserItemAdapter(context, infos, UserFragment.this);
                    recyclerView.setAdapter(adapter);
                } else
                    adapter.update(infos, infoType);
                if (data.getPageNum() == data.getPages()) {
                    adapter.deleteLoadingMore(true);
                    isAll = true;
                } else if (data.getPageNum() < data.getPages()) {
                    page_no++;
                    isAll = false;
                }
            }
        });
    }

    @Override
    public void settledReturn(int code) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                adapter.confirmUpdate();
            }
        });

    }

    @Override
    public void deleteReturn(int code) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                adapter.delete(adapter.getClickPosition());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_total_view:
                getInfoForType(0);
                break;
            case R.id.user_solved_view:
                getInfoForType(1);
                break;
            case R.id.user_setting_bt:
                startActivityForResult(new Intent(context, SettingActivity.class),100);
                break;
        }
    }

    private void getInfoForType(int i) {
        infoType = i;
        refreshLayout.setRefreshing(true);
        infoRefresh();
    }

    public void gotoEditActivity(Info info) {
        Intent intent = new Intent(context, EditActivity.class);
        intent.putExtra("info", info);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
            infoRefresh();
        }
    }

    public void deleteInfo(int id) {
        mPresenter.infoDelete(id);
    }

    public void confirmInfo(int id) {
        mPresenter.infoSettled(id);
    }

    public void updateUser() {
        initUserInfo();
    }
}
